package bueu.bexl;

import static bueu.bexl.utils.TypeUtils.numberValue;
import static bueu.bexl.utils.TypeUtils.stringValue;

public class AddExpr extends BinayExpr {

	public AddExpr(final BexlExpr expr1, final BexlExpr expr2) {
		super(expr1, expr2);
	}

	@Override
	protected final Object evaluate(Object value1, Object value2) {
		if (value1 == null) {
			return value2;
		}
		
		if (value2 == null) {
			return value1;
		}

		if (value1 instanceof Number && value2 instanceof Number) {
			return numberValue(value1) + numberValue(value2);
		}
		
		if (isArray(value1) || isArray(value2)) {
			final Object[] array1 = toArray(value1);
			final Object[] array2 = toArray(value2);
			final int length1 = array1.length;
			final int length2 = array2.length;
			final Object[] array = new Object[length1 + length2];
			System.arraycopy(array1, 0, array, 0, length1);
			System.arraycopy(array2, 0, array, length1, length2);

			return array;
		}

		return stringValue(value1) + stringValue(value2);
	}

	@Override
	public final String toString() {
		return toString("+");
	}
}
